from django.shortcuts import render,HttpResponse,redirect
from django import forms

from App001.utils.bootstrap import BootStrapForm
from App001.utils.bootstrap import BootStrapModelForm
from App001.utils.encrypt import md5
from App001 import models
from App001.utils.code import check_code
class LoginForm(BootStrapForm):
    username=forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput,
        required=True
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )
    # 这个是用来进行md5来进行数据的加密
    def clean_password(self):
        pwd=md5(self.cleaned_data.get("password"))
        return pwd
def login(request):
    """登录页面"""
    if request.method=="GET":
        form=LoginForm()
        return render(request,'login.html',{"form":form})

    form=LoginForm(data=request.POST)
    if form.is_valid():

        user_input_code=form.cleaned_data.pop('code')
        code=request.session.get('image_code','')
        if code.upper()!= user_input_code.upper():
            form.add_error("code",'验证码错误')
            return render(request, 'login.html',{"form": form})

        admin_object=models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password","用户名或密码错误")
            return render(request, 'login.html', {"form": form})

        request.session["info"]={"id":admin_object.id,"name":admin_object.username}
        request.session.set_expiry(60*60*24*7)

        return redirect("/admin/list/")
    return render(request, 'login.html', {"form": form})

from io import BytesIO
def image_code(request):
    """生成验证图片"""
    img,code_string=check_code()
    #写入到自己的session文件中
    request.session['image_code']=code_string
    #对于session来进行60S的超时校验
    request.session.set_expiry(60)

    # print(code_string)
    stream = BytesIO()
    img.save(stream, 'png')

    return HttpResponse(stream.getvalue())
def logout(request):
    """ 注销 """

    request.session.clear()

    return redirect('/login/')